const axios = require('axios');
const path = require('path');
/**
 * 从网络URL下载图片
 * @param {string} imageUrl - 图片的网络地址
 * @returns {Promise<{buffer: Buffer, contentType: string, filename: string}>}
 */
async function downloadImageFromUrl(imageUrl) {
  try {
    // 发送GET请求获取图片，响应类型设为arraybuffer以获取二进制数据
    const response = await axios.get(imageUrl, {
      responseType: 'arraybuffer',
      timeout: 10000, // 10秒超时
    });

    // 从响应头获取文件类型和建议的文件名
    const contentType = response.headers['content-type'] || 'image/jpeg';
    const filename = path.basename(new URL(imageUrl).pathname) || `image-${Date.now()}.jpg`;

    return {
      buffer: Buffer.from(response.data),
      contentType,
      filename,
    };
  } catch (error) {
    console.error('图片下载失败:', error.message);
    throw new Error(`下载图片时出错: ${error.message}`);
  }
}

module.exports = {
  downloadImageFromUrl,
};
